#include <cstring>
#include <iostream>
#include <memory>
#include "UdpServer.hpp"
// ./updserver ip port
void Usage(std::string proc)
{
    std::cout << "Usage: " << proc << " serverip serverport" << std::endl;
}
// ./udpclient ip port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }
    std::string serverip = argv[1];
    int16_t serverport = std::stoi(argv[2]);

    // 创建socket
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "socket error" << std::endl;
    }

    // bind,客户端是否也要绑定？？？也要，因为client也要有自己的ip和port

    // 但是不能和server一样显示的调用bind来绑定
    // 当upp client首次发送数据的时候，OS会自动随机给client进行bind，这是为了防止port冲突
    //

    // 2.直接通信
    //
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    std::string message;
    while (true)
    {
        std::cout << "please enter: " << std::endl;
        std::getline(std::cin, message);
        // 直接发送消息
        sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&server, sizeof(server));
        // 接受来自服务器的消息
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        char buffer[1024];
        ssize_t n = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&peer, &len);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "server echo : " << buffer << std::endl;
        }
    }

    return 0;
}
